package com.zhangxi.websqlit.contact.control;

import com.alibaba.fastjson.JSON;
import com.zhangxi.websqlit.contact.entity.ChartInfoEntity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/chartServer/{userUuid}/{contactUuid}")
@Component
public class ChartWebSocketServer{

    private final static Logger logger = LogManager.getLogger("ChartWebSocketServer");
    /**静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;
    /**concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。*/
    private static ConcurrentHashMap<ChartInfoEntity,ChartWebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话，需要通过它来给客户端发送数据*/
    private Session session;
    private ChartInfoEntity chartInfoEntity;

    /**
     * 连接建立成功调用的方法
     * */
    @OnOpen
    public void onOpen(Session session,
                       @PathParam("userUuid") String userUuid,
                       @PathParam("contactUuid") String contactUuid) {
        logger.info("userUuid:" + userUuid + " contactUuid:" +contactUuid );
        this.session = session;
        chartInfoEntity = new ChartInfoEntity(userUuid, contactUuid);
        if(webSocketMap.containsKey(chartInfoEntity)){
            webSocketMap.remove(chartInfoEntity);
            webSocketMap.put(chartInfoEntity,this);
        }else{
            webSocketMap.put(chartInfoEntity,this);
            //加入set中
            addOnlineCount();
            //在线数加1
        }
        logger.info("user info:" + chartInfoEntity+",online Count:" + getOnlineCount());
        try {
            sendMessage("connect success");
        } catch (IOException e) {
            logger.info("user info:" + chartInfoEntity+",network exception");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if(webSocketMap.containsKey(chartInfoEntity)){
            webSocketMap.remove(chartInfoEntity);
            //从set中删除
            subOnlineCount();
        }
        logger.info("user exit,userUuid:" + chartInfoEntity.getUserUuid()
                + "  contactUuid:" +chartInfoEntity.getContactUuid()
                +",online Count:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("user info:" + chartInfoEntity+",message:" + message);
    }

    /**
     * 实现服务器主动推送
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {
        logger.info("sendMessage:" + message);
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 实现服务器主动推送
     * @param chartInfoEntity
     * @throws IOException
     */
    public void sendMessage(ChartInfoEntity chartInfoEntity) throws IOException {
        String message = jsonDataSuccess("send chart send message success",chartInfoEntity);
        sendMessage(message);
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.info("user info:" + chartInfoEntity+",reason:" + error.getMessage());
        error.printStackTrace();
    }

    public static boolean sendInfo(String message,@PathParam("userUuid") String userUuid,
                                     @PathParam("contactUuid") String contactUuid)  {
        ChartInfoEntity chartInfoEntity = new ChartInfoEntity(userUuid, contactUuid,message);
        logger.info("send messag to:"+chartInfoEntity);
        Set<Map.Entry<ChartInfoEntity, ChartWebSocketServer>> entries = webSocketMap.entrySet();
        for(Map.Entry<ChartInfoEntity , ChartWebSocketServer> item:entries){
            logger.info("webSocketMap:"+ item);
        }
        boolean rst = true;
        if(webSocketMap.containsKey(chartInfoEntity)){
            try {

                webSocketMap.get(chartInfoEntity).sendMessage(chartInfoEntity);
            } catch (IOException e) {
                e.printStackTrace();
                rst = false;
            }
        }else{
            logger.info("user info:" + chartInfoEntity+" not online");
            rst = false;
        }
        return rst;
    }

    public static void sendAll(String messag) throws IOException {
        Set<Map.Entry<ChartInfoEntity, ChartWebSocketServer>> entries = webSocketMap.entrySet();
        for(Map.Entry<ChartInfoEntity , ChartWebSocketServer> item:entries){
            item.getValue().sendMessage(messag);
        }
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        ChartWebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        ChartWebSocketServer.onlineCount--;
    }

    private String jsonDataSuccess(String message,Object data){
        Map<String,Object> map = new HashMap<>();
        map.put("success",true);
        map.put("msg",message);
        map.put("data",data);
        return JSON.toJSONString(map);
    }

}
